package com.db.httpclient;

import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;

public class Client {
	
	private String host;
	private static final int PORT = 8080;
	
	public static void main(String[] args) throws IOException {
		Client client = new Client("localhost");
		System.out.println(client.get("/"));
	}
	
	public Client(String host) {
		this.host = host;
	}
	
	public String get(String uri) throws IOException {
		String request = String.format("GET %s HTTP/1.0\r\nHost: %s\r\n", uri, host);
		return makeRequest(request);
	}
	
	private String makeRequest(String request) throws IOException {
		Socket s = new Socket(host, PORT);
		
		final PrintStream ps = new PrintStream(s.getOutputStream(), true);
		final Scanner scanner = new Scanner(s.getInputStream());
		
		ps.print(request);
		
		StringBuilder sb = new StringBuilder();
		while (scanner.hasNext()) {
			sb.append(scanner.nextLine());
			sb.append("\r\n");
		}
		
		scanner.close();
		s.close();
		
		if (sb.length() > 0)
			return sb.toString();
		else
			return "server closed connection\r\n";
	}
}
